package org.example.cake.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.example.cake.common.Rep;
import org.example.cake.entity.Category;
import org.example.cake.entity.Festival;
import org.example.cake.service.FestivalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/festival")
public class FestivalController {

    @Autowired
    private FestivalService festivalService;

    /**
     * 查询所有节日
     * @return 节日集合
     */
    @GetMapping("/getFestivals")
    public Rep getFestivals(){
        List<Festival> festivals = this.festivalService.getFestivals();
        return new Rep().addData("festivals", festivals);
    }

    /**
     * 后台查询所有节日活动分页或者根据活动名称模糊查询节日
     * @author 徐
     * @param festivalname 节日名称
     * @date 2025-07-31
     * @return 节日集合
     */
    @GetMapping("/selectFestivalPageEnd")
    public Rep selectFestivalPageEnd(@Param("page") Integer page, @Param("pageSize") Integer pageSize
            , @Param("festivalname") String festivalname,
              @Param("discountid") Integer discountid) {
        // 开启分页
        PageHelper.startPage(page,pageSize);
        // 执行查询
        List<Festival> list = festivalService.selectFestivalPageEnd(festivalname, discountid);
        // 创建分页对象
        PageInfo<Festival> festivalPageInfo=new PageInfo<>(list);
        // 返回
        return new Rep().addData("festivalPageInfo", festivalPageInfo);
    }

    /**
     * //后台节日活动删除（根据id删除）
     * @author 徐
     * @param festivalid 节日id
     * @date 2025-07-31
     * @return 节日id
     */
    @PostMapping("/deleteFestivalEnd")
    public String deleteFestivalEnd(@RequestParam("festivalid") Integer festivalid) {
        return festivalService.deleteFestivalEnd(festivalid);
    }

    /**
     * //新增后台节日活动信息
     * @author 徐
     * @param festival 节日对象
     * @date 2025-07-31
     * @return 受影响的行数
     */
    @PostMapping("/insertFestivalEnd")
    public String insertFestivalEnd(@RequestBody Festival festival) {
        return festivalService.insertFestivalEnd(festival);
    }

    /**
     * //修改后台节日信息
     * @author 徐
     * @param festival 节日对象
     * @date 2025-07-31
     * @return 受影响的行数
     */
    @PostMapping("/updateFestivalEnd")
    public String updateFestivalEnd(@RequestBody  Festival festival) {
        return festivalService.updateFestivalEnd(festival);
    }


    /**
     * 新增活动
     * @author 罗江锦
     * @param festival 活动实体
     * @return 统一响应对象
     */
    @PostMapping("/insertFestivalSky")
    public Rep insertFestivalSky(@RequestBody Festival festival) {
        Rep rep = new Rep();

        try {
            // 验证必填字段
            if (festival.getFestivalname() == null || festival.getFestivalname().trim().isEmpty()) {
                rep.setCode(400);
                rep.setMsgerr("活动名称不能为空");
                return rep;
            }

            if (festival.getFestivalstart() == null || festival.getFestivalend() == null) {
                rep.setCode(400);
                rep.setMsgerr("活动时间不能为空");
                return rep;
            }

//            if (festival.getFestivalstart().after(festival.getFestivalend())) {
//                rep.setCode(400);
//                rep.setMsgerr("开始时间不能晚于结束时间");
//                return rep;
//            }

            if (festival.getFestivalimg() == null || festival.getFestivalimg().trim().isEmpty()) {
                rep.setCode(400);
                rep.setMsgerr("请上传活动图片");
                return rep;
            }

            System.out.println("接收到的活动数据: " + festival);

            // 调用服务层添加活动
            int result = festivalService.insertFestivalSky(festival);

            if (result > 0) {
                rep.setCode(200);
                rep.setMsgerr("添加活动成功");
                rep.addData("festivalId", festival.getFestivalid());
            } else {
                rep.setCode(500);
                rep.setMsgerr("添加分类失败");
            }
        } catch (Exception e) {
            rep.setCode(500);
            rep.setMsgerr("添加活动时出错: " + e.getMessage());
            e.printStackTrace(); // 打印错误堆栈，便于调试
        }
        return rep;
    }

    /**
     * 查询可用优惠券列表（供前端下拉框使用）
     * @author 罗江锦
     * 与前端 ajax 请求的 url 完全匹配
     */
    @GetMapping("/selectAvailableDiscounts")
    public Rep selectAvailableDiscounts() {
        Rep rep = new Rep();
        try {
            List<Map<String, Object>> discountList = festivalService.selectAvailableDiscountSky();
            rep.setCode(200);
            rep.setMsgerr("查询成功");
            rep.addData("discountList",discountList);
        } catch (Exception e) {
            rep.setCode(500);
        }
        return rep;
    }

    /**
     * 根据ID获取活动详情
     * @author 罗江锦
     * @param festivalid 活动ID
     * @return 活动详情响应实体
     */
    @GetMapping("/{festivalid}")
    public ResponseEntity<Map<String, Object>> getFestivalById(
            @PathVariable Integer festivalid) {

        Map<String, Object> response = new HashMap<>();
        response.put("timestamp", System.currentTimeMillis());

        try {
            // 参数验证
            if (festivalid == null || festivalid <= 0) {
                response.put("code", 400);
                response.put("message", "节日ID必须为正整数");
                return ResponseEntity.badRequest().body(response);
            }

            // 查询节日信息
            Festival festival = festivalService.selectByPrimaryKeySky(festivalid);

            if (festival == null) {
                response.put("code", 404);
                response.put("message", "节日不存在");
                return ResponseEntity.ok(response);
            }

            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", festival);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "查询节日信息出错: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新活动信息
     * @author 罗江锦
     * @param festival 活动实体
     * @return 统一响应对象
     */
    @PostMapping("/updateFestivalendSky")
    public Rep updateFestivalendSky(@RequestBody Festival festival) {
        Rep rep = new Rep(); // 初始化统一响应对象

        try {
            // 验证必填参数
            if (festival.getFestivalid() == null) {
                rep.setCode(400);
                rep.setMsgerr("活动ID不能为空");
                return rep;
            }

            if (festival.getFestivalname() == null || festival.getFestivalname().trim().isEmpty()) {
                rep.setCode(400);
                rep.setMsgerr("活动名称不能为空");
                return rep;
            }

            if (festival.getFestivalstart() == null || festival.getFestivalend() == null) {
                rep.setCode(400);
                rep.setMsgerr("活动时间不能为空");
                return rep;
            }

//            if (festival.getFestivalstart().after(festival.getFestivalend())) {
//                rep.setCode(400);
//                rep.setMsgerr("开始时间不能晚于结束时间");
//                return rep;
//            }

            // 执行更新操作
            int result = festivalService.updateFestivalSky(festival);

            if (result > 0) {
                rep.setCode(200); // 成功状态码
                rep.setMsgerr("修改成功");
                rep.addData("修改成功后的活动：",festival); // 返回更新后的活动数据
            } else {
                rep.setCode(500); // 失败状态码
                rep.setMsgerr("修改失败，活动不存在或未修改内容");
            }
        } catch (Exception e) {
            rep.setCode(500);
            rep.setMsgerr("更新活动时出错: " + e.getMessage());
        }
        return rep;
    }

    /**
     * 根据ID删除活动
     * @author 罗江锦
     * @param festivalid 活动ID
     * @return 响应实体
     */
    @DeleteMapping("/{festivalid}")
    public ResponseEntity<Map<String, Object>> deleteFestivalSky(
            @PathVariable Integer festivalid) {

        // 统一响应格式
        Map<String, Object> response = new HashMap<>();
        response.put("timestamp", System.currentTimeMillis());

        try {
            // 参数验证
            if (festivalid == null || festivalid <= 0) {
                response.put("code", 400);
                response.put("message", "活动ID必须为正整数");
                return ResponseEntity.badRequest().body(response);
            }

            // 执行业务逻辑（int返回值）
            int result = festivalService.deleteFestivalSky(festivalid);

            if (result > 0) {
                response.put("code", 200);
                response.put("message", "删除成功");
                response.put("data", result); // 返回影响的行数
                return ResponseEntity.ok(response);
            } else if (result == 0) {
                response.put("code", 404);
                response.put("message", "节日不存在或已被删除");
                return ResponseEntity.ok(response);
            } else {
                response.put("code", 500);
                response.put("message", "删除失败");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "删除活动时出错: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    /**
     * //后台根据id查询节日活动是否存在
     * @author 徐
     * @param festivalid 节日id
     * @date 2025-08-04
     * @return 受影响行数
     */
    @GetMapping("/selectById")
    public Rep selectById(@RequestParam("festivalid") Integer festivalid) {
        Festival selectById = this.festivalService.selectById(festivalid);
        return new Rep().addData("data",selectById);

    }

}
